import React, { useEffect, useState } from 'react';
import {
  Form,
  Modal,
  Grid,
  Input,
  InputNumber,
  TimePicker,
  Select,
  TreeSelect,
} from '@arco-design/web-react';
import * as Model from '@/services/model';
import Api from '@/services/api';
const { useForm } = Form;
const { Row, Col } = Grid;
interface DetailModalProps {
  orgnizeInfo?: Model.Orgnize | false;
  parent?: Model.Orgnize | false;
  onCancel: () => void;
  onOk: (params: Model.Orgnize) => void;
}
const generateTreeData = (list) => {
  return list.map((e) => {
    const children = Array.isArray(e.children)
      ? generateTreeData(e.children)
      : null;
    return { ...e, key: e.id, title: e.name, children };
  });
};
export const DetailModal = (props: DetailModalProps) => {
  const [form] = useForm();
  const [treeData, setTreeData] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchData = async () => {
    setLoading(true);
    const res = await Api.orgnizeList({}).catch(() => {
      return false;
    });
    if (res) {
      setTreeData(generateTreeData(res.list));
    }
    setLoading(false);
  };

  useEffect(() => {
    if (props.orgnizeInfo !== false) {
      fetchData();
      form.setFieldsValue(props.orgnizeInfo);
      form.setFieldValue('parent', props.orgnizeInfo.id);
    }
  }, [props.orgnizeInfo]);

  const submit = async () => {
    const res = await form.validate();
    console.log(res);
    if (res) {
      props.onOk(res);
    }
  };
  return (
    <Modal
      visible={props.orgnizeInfo !== false}
      title={`${
        props.orgnizeInfo && props.orgnizeInfo.id ? '修改' : '新增'
      }组织`}
      mountOnEnter
      unmountOnExit
      onCancel={props.onCancel}
      onOk={submit}
      alignCenter={false}
      okText="提交"
      cancelText="取消"
      style={{ width: 600 }}
    >
      <Form
        form={form}
        labelAlign="left"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
      >
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item label="组织名称" field="name" required>
              <Input placeholder="请输入组织名称" allowClear />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
